package com.ruoyi.web.controller.system;

import java.util.Date;
import java.util.List;
import java.util.Objects;
import java.util.Set;

import com.alibaba.fastjson2.JSONObject;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.model.RegisterBody;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.framework.web.service.SysRegisterService;
import com.ruoyi.system.service.ISysConfigService;
import com.ruoyi.system.service.ISysUserService;
import com.ruoyi.web.ydz.domain.PointsRecord;
import com.ruoyi.web.ydz.domain.SmsVerification;
import com.ruoyi.web.ydz.domain.UserDocument;
import com.ruoyi.web.ydz.mapper.PointsRecordMapper;
import com.ruoyi.web.ydz.mapper.UserDocumentMapper;
import com.ruoyi.web.ydz.util.messageUtil.SendSms;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.*;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysMenu;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.domain.model.LoginBody;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.framework.web.service.SysLoginService;
import com.ruoyi.framework.web.service.SysPermissionService;
import com.ruoyi.system.service.ISysMenuService;

import javax.annotation.Resource;

/**
 * 登录验证
 *
 * @author DRX
 */
@RestController
public class SysLoginController extends BaseController {
    @Resource
    private SysLoginService loginService;

    @Resource
    private ISysMenuService menuService;

    @Resource
    private SysPermissionService permissionService;

    @Resource
    private SendSms sendSms;

    @Resource
    private ISysConfigService configService;

    @Resource
    private SysRegisterService registerService;

    @Resource
    private UserDocumentMapper userDocumentMapper;

    @Resource
    private PointsRecordMapper pointsRecordMapper;

    @Resource
    private ISysUserService userService;

    /**
     * 登录方法
     *
     * @param loginBody 登录信息
     * @return 结果
     */
    @PostMapping("/login")
    public AjaxResult login(@RequestBody LoginBody loginBody) {
        AjaxResult ajax = success();
        // 生成令牌
        String token = loginService.login(loginBody.getUsername(), loginBody.getPassword(), loginBody.getCode(),
                loginBody.getUuid());
        ajax.put(Constants.TOKEN, token);
        return ajax;
    }

    /*手机号码登录*/
    @PostMapping("/phoneLogin")
    public AjaxResult phoneLogin(@RequestBody SmsVerification smsVerification) {
        return sendSms.phoneLogin(smsVerification);
    }

    /*更换手机号码*/
    @RequestMapping("/changePhoneNum")
    public AjaxResult changePhoneNum(@RequestBody SmsVerification smsVerification){
        return sendSms.changePhoneNum(smsVerification);
    }

    /*手机号码注册*/
    // @PostMapping("/phoneRegister")
    // 使用原有注册接口
    public AjaxResult phoneRegister(@RequestBody SmsVerification smsVerification) {
        RegisterBody registerBody = new RegisterBody();
        BeanUtils.copyProperties(smsVerification, registerBody);
        registerBody.setUsername(smsVerification.getPhone());

        if (!("true".equals(configService.selectConfigByKey("sys.account.registerUser")))) {
            return error("当前系统没有开启注册功能！");
        }
        AjaxResult ajaxResult = sendSms.proofCode(smsVerification);
        if (!Objects.isNull(ajaxResult.get("data"))) {
            if (Boolean.parseBoolean(String.valueOf(ajaxResult.get("data")))) {
                String msg = registerService.register(registerBody,"");
                return StringUtils.isEmpty(msg) ? success() : error(msg);
            } else {
                return ajaxResult;
            }
        } else {
            return ajaxResult;
        }
    }

    /*找回密码*/
    @PostMapping("/retrievePwd")
    public AjaxResult retrievePwd(@RequestBody SysUser user){

        AjaxResult ajaxResult = new AjaxResult();

        if (StringUtils.isEmpty(user.getPhonenumber())){
            ajaxResult.put("code", 200);
            ajaxResult.put("msg", "请输入账号");
            return ajaxResult;
        } else if (StringUtils.isEmpty(user.getPassword())) {
            ajaxResult.put("code",200);
            ajaxResult.put("msg","请输入重置后密码");
            return ajaxResult;
        }

        SysUser sysUser = userService.selectUserByname(user.getPhonenumber());
        if (Objects.isNull(sysUser)){
            ajaxResult.put("code",200);
            ajaxResult.put("msg","暂无当前用户信息,请联系管理员");
            return ajaxResult;
        }

        /*校验修改账号是否为当前登录用户*/
        SysUser loginuser = SecurityUtils.getLoginUser().getUser();
        if (!loginuser.getPhonenumber().equals(user.getPhonenumber())){
            ajaxResult.put("code",200);
            ajaxResult.put("msg","手机号码匹配错误,请输入账号绑定手机号码");
            return ajaxResult;
        }

        /*校验验证码*/
        if (!Objects.isNull(user.getSmsVerificationDTO())){
            SmsVerification smsVerification = new SmsVerification();
            BeanUtils.copyProperties(user.getSmsVerificationDTO(),smsVerification);

            AjaxResult sendSmsResult = sendSms.proofCode(smsVerification);
            if (!Boolean.parseBoolean(String.valueOf(sendSmsResult.get("data")))){
                return sendSmsResult;
            }
        }else {
            ajaxResult.put("code",200);
            ajaxResult.put("msg","验证码输入错误，请校验后重新输入");
            return ajaxResult;
        }

        sysUser.setPassword(SecurityUtils.encryptPassword(user.getPassword()));
        //user.setUpdateBy(getUsername());
        return toAjax(userService.resetPwd(sysUser));

    }

    /*发送验证码*/
    @PostMapping("/sendSmsCode")
    public JSONObject sendSmsCode(@RequestBody SmsVerification smsVerification) throws Exception {
        return sendSms.sendMessage(smsVerification);
    }

    /*校验验证码*/
    @PostMapping("/checkSmsCode")
    public AjaxResult checkSmsCode(@RequestBody SmsVerification smsVerification){
        return sendSms.proofCode(smsVerification);
    }

    /**
     * 获取用户信息
     *
     * @return 用户信息
     */
    @GetMapping("getInfo")
    public AjaxResult getInfo() {
        SysUser user = SecurityUtils.getLoginUser().getUser();
        // 角色集合
        Set<String> roles = permissionService.getRolePermission(user);
        // 权限集合
        Set<String> permissions = permissionService.getMenuPermission(user);
        // 用户APP信息
        UserDocument userDocument = userDocumentMapper.selectUserDocumentByUserId(user.getUserId());
        // 签到信息
        List<Date> currentWeek = sendSms.getCurrentWeek();
        PointsRecord pointsRecord = new PointsRecord();
        pointsRecord.setCurrentWeek(currentWeek);
        pointsRecord.setUserId(user.getUserId());
        List<PointsRecord> signInRecord = pointsRecordMapper.getSignInRecord(pointsRecord);

        /*查询用户当日是否签到*/
        PointsRecord todayPoints = pointsRecordMapper.checkSignIn(user.getUserId());

        AjaxResult ajax = success();
        ajax.put("user", user);
        ajax.put("roles", roles);
        ajax.put("permissions", permissions);
        ajax.put("userDocument", userDocument);
        ajax.put("signInRecord", signInRecord);
        ajax.put("signIn", !Objects.isNull(todayPoints));

        return ajax;
    }

    /**
     * 获取路由信息
     * 
     * @return 路由信息
     */
    @GetMapping("getRouters")
    public AjaxResult getRouters()
    {
        Long userId = SecurityUtils.getUserId();
        List<SysMenu> menus = menuService.selectMenuTreeByUserId(userId);
        return success(menuService.buildMenus(menus));
    }
}
